#include "global.h"
#include "serial.h"
#include "uart2.h"
#include "cmdline.h"

/*
void tx(char data)
{
    while (!(UCSR0A & (1<<UDRE)));
    UDR0 = data;
}
*/
char rx(void)
{
	while ( !(UCSR0A & (1<<RXC0)) );
	return UDR0;
}

typedef struct {
	u08 command;
	u08 param1;
	u08 param2;
	u08 param3;
	u08 param4;
} packet_struct;

packet_struct command_data;
packet_struct *command_packet;
packet_struct rx_data;
packet_struct *rx_packet;

//flags

u08 data_received;

u16 data_count=0;
u08 header_found;

void serialInit(void)
{
    command_packet = &command_data;
	rx_packet=&rx_data;

	if (CAM_UART == 0)
		uart0Init();
	else
		uart1Init();
		
    uartSetBaudRate(CAM_UART, 115200);
	uartSetRxHandler(CAM_UART, rxDataHandler);
	
	return;
}

void putchr(char c)
{

  loop_until_bit_is_set(UCSRA, UDRE);
  UDR = c;
}



// Send a C (NUL-terminated) string down the UART Tx.
 
void printstr(const char *s)
{

  while (*s)
    {
      if (*s == '\n') putchr('\r');
      putchr(*s++);
    }
}

void serialTest(void)										//< transmits command data through serial port
{
	uart0SendByte(0xaa);
	uart0SendByte(0x0a);
}

void rxDataHandler(u08 data)										//< interrupt-based incoming data handler
{
	//u16 rx_data;

/////////////////////    
    //uart0SendByte(data);
	cmdlineInputFunc(data);
/////////////////////////////////    
	if (data_received==FALSE)
		{/*
		 if (data == CAM_COMMAND_HEADER)							//< found header?
			{
		 	 data_count=0;
		 	 header_found=TRUE;
			}
		else
			if (header_found)								//< save command payload
				*((u08*)rx_packet+data_count++)=data;

		if (data_count == CAM_RX_PACKET_SIZE)							//< complete packet received?
			{
		 	 header_found=FALSE;
		 	 switch (rx_packet->command)							//< decode packet
				{
			 	 case CAM_ACK:
					if (rx_packet->param1==command_packet->command)
			 			ack_received=TRUE;
					break;
			 	 case CAM_NAK:
					nack_received=TRUE;
					break;
			 	 case CAM_SYNC:
					sync_received=TRUE;
					break;
			 	 case CAM_DATA:
					picture_size=rx_packet->param4;
					picture_size=picture_size<<8;
 					picture_size|=rx_packet->param3;
					picture_size=picture_size<<8;
					picture_size|=rx_packet->param2;
					data_received=TRUE;
					data_count=0;
					break;
			 	 default: break;
				}
		 	}*/
		} else {
               /*											//< received picture data
		 data_count++;

		 if (data_count==3)									//< retrieve packet size
			data_size=data;
		 if (data_count==4)
			{
			 rx_data=data;
			 data_size|=rx_data<<8;
			}

		 if (data_count>4 && (data_count<=(data_size+4)))					//< save picture data into buffer
			*(external_buffer++)=data;

		 if (data_count==(data_size+6))								//< indicate complete packet received
			packet_ready=TRUE;
			*/
		}
}
